package com.newtouch.cq.lang.util;

import cn.hutool.core.util.StrUtil;
import com.newtouch.cq.lang.em.DownTypeEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 文件工具类
 *
 * @author alex
 * @Date: 2021/1/7
 */
public class FileUtils {

    /**
     * 在线视频播放
     *
     * @param file
     */
    public static void vedio(File file) {
        down(file, DownTypeEnum.PLAY);
    }

    /**
     * 在线视频播放
     *
     * @param file
     */
    public static void onlineRead(File file) {
        down(file, DownTypeEnum.ONLINE_READING);
    }

    /**
     * 在线视频播放
     *
     * @param file
     */
    public static void down(File file, DownTypeEnum downType) {
        HttpServletResponse response = ServletUtils.getResponse();
        HttpServletRequest request = ServletUtils.getRequest();
        response.reset();

        try {
            //获取响应的输出流
            OutputStream outputStream = response.getOutputStream();
            if (file.exists()) {
                RandomAccessFile targetFile = new RandomAccessFile(file, "r");
                long fileLength = targetFile.length();

                //播放
                if (DownTypeEnum.PLAY == downType) {
                    //获取从那个字节开始读取文件
                    String rangeString = StrUtil.isEmpty(request.getHeader("Range")) ?
                            "bytes=0-" + targetFile.length() : request.getHeader("Range");
                    long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                    //设置内容类型
                    response.setHeader("Content-Type", "video/mp4");
                    //设置此次相应返回的数据长度
                    response.setHeader("Content-Length", String.valueOf(fileLength - range));
                    //设置此次相应返回的数据范围
                    response.setHeader("Content-Range", "bytes " + range + "-" + (fileLength - 1) + "/" + fileLength);
                    //返回码需要为206，而不是200
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    //设定文件读取开始位置（以字节为单位）
                    targetFile.seek(range);
                } else if (DownTypeEnum.ONLINE_READING == downType) {
                    response.setContentType("text/html; charset=UTF-8");//文本&编码
                    response.setContentType("application/pdf");//pdf
                } else {//下载

                    //设置响应头，把文件名字设置好
                    response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
                    //设置文件长度
                    response.setHeader("Content-Length", String.valueOf(fileLength));
                    //解决编码问题
                    response.setHeader("Content-Type", "application/octet-stream");
                }


                byte[] cache = new byte[1024 * 300];
                int flag;
                while ((flag = targetFile.read(cache)) != -1) {
                    outputStream.write(cache, 0, flag);
                }
            } else {
                String message = "file:" + file.getName() + " not exists";
                //解决编码问题
                response.setHeader("Content-Type", "application/json");
                outputStream.write(message.getBytes(StandardCharsets.UTF_8));
            }

            outputStream.flush();
            outputStream.close();

        } catch (FileNotFoundException e) {

        } catch (IOException e) {

        }
    }

    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

}
